import {search} from '@/api/codeTypeApi'
import SessionUtil from "@/lib/SessionUtil";

const codeTypeServiceMap = new Map();
let codeTypeService = {

    /**
     *根据codeType获取列表
     */
    getCodeTypeList: function (params) {
        if (!params.filter) {
            params.filter = {}
        }
        let codes = codeTypeService.readCodes(params)
        const generateKey = codeTypeService.generateKey(params);
        let serviceFunction = codeTypeServiceMap.get(generateKey)
        if (serviceFunction) {
            if (codes){
                codeTypeServiceMap.delete(generateKey)
            }
            return serviceFunction;
        }
        let result = new Promise(resolve => {
            if (codes) {
                resolve(codes)
            } else {
                search(params).then(data => {
                    codeTypeService.writeCodes(params, data)
                    resolve(data)
                })
            }
        })
        codeTypeServiceMap.set(generateKey,result)
        return result;
    },
    /**
     * 写缓存数据
     */
    writeCodes: function (params, datas) {
        if (params.forceFetch === true || params.filter.forceFetch === true) {
            return
        }
        let key = codeTypeService.generateKey(params)
        SessionUtil.setItem(key, JSON.stringify(datas))
    },
    /**
     * 读缓存数据
     */
    readCodes: function (params) {
        if (params.codeType.indexOf('NO_CACHE') !== -1) {
            return
        }
        if (params.forceFetch === true || params.filter.forceFetch === true) {
            return
        }
        let key = codeTypeService.generateKey(params)
        let codes = SessionUtil.getItem(key)
        if (codes) {
            codes = JSON.parse(codes)
        }
        return codes
    },
    /**
     * 生成缓存key
     */
    generateKey: function (params) {
        let key = params.codeType
        if (params.code) {
            key = key + '_' + params.code
        }
        if (params.filter && params.filter.md5) {
            key += '_' + params.filter.md5
        } else {
            Object.keys(params.filter).forEach(filterKey => {
                key += '_' + filterKey + '_' + params.filter[filterKey]
            })
        }
        return key
    },
}
export default codeTypeService;